# ------------------------------------------------------------------------------
# Builds table of adverse outcome rates under various restrictions for appendix
# Author: Cassidy Shubatt <cshubatt@gmail.com>
# To run: bash 09_adverse_event_tbl.sh
# ------------------------------------------------------------------------------

# Libraries --------------------------------------------------------------------
library(here)
library(yaml)
library(data.table)
library(tidyverse)
library(glue)
library(testit) # other()
library(broom)
library(lfe)
library(xtable)

u <- modules::use(here::here("lib", "util.R"))
overnight_lab <- ""
temp <- here::here(
  "code", "03_score_diagnostics", "temp", "07_adverse_event_tbl"
)
dir.create(temp, showWarnings = FALSE)

# Helpers ----------------------------------------------------------------------
get_mean_se <- function(
                        outcome = "macetrop_pos_or_death_030",
                        x_var = "tile_stent_or_cabg_005_tested",
                        restriction_var = "no_restr") {
  table_vars <- c(outcome, x_var, restriction_var)
  df <- copy(cohort) %>%
    setnames(table_vars, c("outcome", "x_var", "restriction_var")) %>%
    mutate(x_var = factor(x_var)) %>%
    filter(!restriction_var)

  outcome_lab <- case_when(
    outcome == "yhat" ~ "mean_yhat",
    restriction_var == "no_restr" ~ "adverse_all",
    restriction_var == "has_ecg" ~ "adverse_noecg",
    restriction_var == "has_sameday_tn" ~ "adverse_notn",
    TRUE ~ restriction_var
  )

  fit <- felm(outcome ~ x_var + 0 | 0 | 0 | ptid, data = df)
  tidy_fit <- tidy(fit) %>%
    setnames(
      c("term", "estimate"),
      c("x_var", "mean")
    ) %>%
    select(x_var, mean, std.error) %>%
    mutate(x_var = str_remove(x_var, "x_var") %>% as.numeric()) %>%
    gather(key = "Term", value = "outcome", -x_var) %>%
    mutate(outcome = as.character(outcome %>% round(3))) %>%
    mutate(
      outcome = ifelse(Term == "std.error", glue("({outcome})"), outcome)
    ) %>%
    setnames("outcome", outcome_lab)

  return(tidy_fit)
}

# Load Data --------------------------------------------------------------------
message("Loading data...")
paths <- read_yaml(here::here("lib", "filepaths.yml"))
cohort <- readRDS(glue(paths$analysis$test_cohort)) %>%
  filter(!exclude) %>%
  mutate(macetrop_pos_or_death_030 = macetrop_030_pos) %>%
  # mutate(macetrop_pos_or_death_030 = macetrop_030_pos | death_030_day) %>%
  mutate(has_sameday_tn = !is.na(maxtrop_sameday)) %>%
  filter(!test_010_day) %>%
  mutate(yhat = p__ensemble__stent_or_cabg_010_day__tested) %>%
  mutate(no_restr = FALSE)

# Adverse Means ----------------------------------------------------------------
message("Getting mean adverse outcome rates...")
comb_rates <- get_mean_se(outcome = "yhat") %>%
  u$safe_left_join(get_mean_se()) %>%
  u$safe_left_join(get_mean_se(restriction_var = "has_ecg")) %>%
  u$safe_left_join(get_mean_se(restriction_var = "has_sameday_tn"))

message("Formatting table...")
comb_clean <- comb_rates %>%
  .[order(.[["x_var"]]), ] %>%
  mutate(x_var = ifelse(Term == "std.error", "", x_var)) %>%
  select(-Term)

# Save -------------------------------------------------------------------------
message("Saving adverse appendix table...")
xt <- xtable(comb_clean)
print(
  xt,
  type = "latex", file = file.path(temp, "adverse_outcome_tbl.tex"),
  include.rownames = FALSE
)

message("Done.")
